package com.eobard.mq;

import com.eobard.entity.MqMessage;
import com.eobard.service.MqMessageService;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * @Author: Eobard Gu
 * @Date: 2025-07-17
 * @Description: TODO
 */
@Service
public class RabbitService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    /**
     * 发送消息
     *
     * @param exchange   交换机
     * @param routingKey 路由key
     * @param message    消息
     * @return
     */
    public boolean sendMessage(String exchange, String routingKey, Object message) {
        //创建CorrelationData对象:每条消息绑定一个“唯一标识”,用于生产者Confirm回调追踪
        CorrelationData data = new CorrelationData();

        //消息持久化:默认情况下消息业务id和最后一次发送id一致(注意：这里持久化一定要在发送消息之前,否则这条sql会在回调函数中提交事务！！)
        MqMessage mqMessage = new MqMessage(data.getId(), data.getId(), exchange, routingKey, message.toString(), false);
        mqMessageService.save(mqMessage);

        //发送消息
        rabbitTemplate.convertAndSend(exchange, routingKey, message, data);

        return true;
    }

}
